package com.cszy.yydqbfq.viewmodel

import AudioLoadRepository
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.cszy.yydqbfq.base.BaseViewModel
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.bean.SongListBean
import com.cszy.yydqbfq.common.PlaylistRepository
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.lzx.starrysky.SongInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.litepal.LitePal

class SongListViewModel :BaseViewModel(){

    private lateinit var AudioLoadRespository: AudioLoadRepository
    fun init(context: Context) {
        AudioLoadRespository = AudioLoadRepository(context.applicationContext)
    }
    private val repository = PlaylistRepository()
    private val _playlists = MutableLiveData<List<SongListBean>>()
    val playlists: LiveData<List<SongListBean>> = _playlists

    private val _currentPlaylist = MutableLiveData<SongListBean?>()
    val currentPlaylist: LiveData<SongListBean?> = _currentPlaylist
    // 新增选中状态管理
    private val _selectedItems = mutableSetOf<Long>() // 存储选中的歌单ID
    val selectedItems: Set<Long> get() = _selectedItems


    init {
        loadPlaylists()
    }
    // 切换选中状态
    fun toggleItemSelection(itemId: Long) {
        if (_selectedItems.contains(itemId)) {
            _selectedItems.remove(itemId)
        } else {
            _selectedItems.add(itemId)
        }
    }
    // 删除所有选中的歌单
    fun deleteSelectedPlaylists() {
        _selectedItems.forEach { id ->
            repository.deletePlaylist(id)
        }
        _selectedItems.clear()
        loadPlaylists() // 刷新列表
    }

    /**
     * 更新歌单信息
     */
    fun updatedPlaylist(id: Long, name: String, cover: String) {
        if (repository.updatePlaylist(id, name, cover)) {
            loadPlaylists()
        }
    }


    fun loadPlaylists() {
        _playlists.value = repository.getAllPlaylists()
    }

    fun addPlaylist(name: String, cover: String) {
        if (repository.addPlaylist(name, cover)) {
            loadPlaylists()
        }
    }

    fun deletePlaylist(id: Long) {
        if (repository.deletePlaylist(id)) {
            loadPlaylists()
        }
    }

    fun loadPlaylistDetail(id: Long) {
        _currentPlaylist.value = repository.getPlaylistById(id)
    }

    fun addSongToPlaylist(playlistId: Long, title: String, artist: String, duration: Long) {
        val song = Song(
            title = title,
            artist = artist,
            duration = duration,
            songlistbean_id = playlistId
        )
        if (repository.addSongToPlaylist(playlistId, song)) {
            loadPlaylistDetail(playlistId)
        }
    }

    fun removeSongFromPlaylist(songId: Long, playlistId: Long) {
        if (repository.removeSongFromPlaylist(songId)) {
            loadPlaylistDetail(playlistId)
        }
    }

    //数据库歌单列表的音乐转songInfo
    fun convertToSongInfoList(musicList: List<Song>): List<SongInfo> {
        return musicList.map { song ->
            SongInfo().apply {
                songId = song.id.toString() // 使用数据库中的ID而不是索引
                songUrl = song.uri
                songName = song.title
                artist = song.artist
                songCover = song.cover
                duration = song.duration
                decode = false // 默认不需要解码
            }
        }
    }

    /**
     * 从本地获取音频列表(有则从数据库获取)
     */
    suspend fun getAudioInfoListSync(): List<AudioItemBean> = withContext(Dispatchers.IO) {
        try {
            val localList = LitePal.findAll(AudioItemBean::class.java)
            if (localList.isNotEmpty()) {
                return@withContext localList
            }
            val remoteList = AudioLoadRespository.loadAudioFiles()
            LitePal.saveAll(remoteList)
            remoteList
        } catch (e: Exception) {
            Log.e("AudioViewModel", "Error fetching audio list", e)
            emptyList()
        }
    }

}